<template>
    <el-dialog v-model="show" title="添加用户" @close="emit('hide')">
        <el-form ref="formRef" :model="form" :rules="rules">
            <el-form-item prop="username" label="账号" label-width="100px">
                <el-input v-model="form.username" autocomplete="off" />
            </el-form-item>
            <el-form-item prop="nickName" label="姓名" label-width="100px">
                <el-input v-model="form.nickName" autocomplete="off" />
            </el-form-item>
            <el-form-item prop="email" label="邮箱" label-width="100px">
                <el-input v-model="form.email" autocomplete="off" />
            </el-form-item>
            <el-form-item  label="密码" label-width="100px">
                <el-input v-model="form.password" autocomplete="off" type="password" :disabled="data" />
            </el-form-item>
            <el-form-item label="备注" label-width="100px">
                <el-input v-model="form.note" autocomplete="off" type="textarea" />
            </el-form-item>
            <el-form-item label="是否启用" label-width="100px">
                <el-radio-group v-model="form.status" class="ml-4">
                    <el-radio label="1" size="large">是</el-radio>
                    <el-radio label="0" size="large">否</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="emit('hide')">取消</el-button>
                <el-button @click="sureFn" type="primary"> 确定 </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { user } from '@/api';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { reactive, ref, watch } from 'vue';

const searchFormRef = ref<FormInstance>();
const form = reactive<IRegisterUserParams>({
    username: "",
    nickName: "",
    email: "",
    password: "",
    note: "",
    status: 0,
})

const emit = defineEmits(["hide", "refresh"])

const validUsername = (rule: any, value: any, callback: any) => {
    const reg = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,18}$/
    if (value === '') {
        callback(new Error('请输入密码'))
    } else if (!reg.test(value)) {
        callback(new Error('密码必须是由6-18位英文(含大小写)+数字组成'))
    } else {
        callback()
    }
}
const rules = {
    username: [
        { required: true, message: "请输入用户名", trigger: "blur" },
        { min: 2, max: 20, message: "用户名要在2~20个字符之间", trigger: "blur" },
    ],
    nickName: [
        { required: true, message: "请输入姓名", trigger: "blur" },
        { min: 2, max: 16, message: "姓名要在2~16个字符之间", trigger: "blur" },
    ],
    email: [
        { required: true, message: "请输入邮箱", trigger: "blur" },
        {
            type: "email",
            message: "请填空正确的邮箱地址",
            trigger: ["blur", "change"],
        },
    ],
    password: [
        { required: true, validator: validUsername, trigger: 'blur' }
    ],
};

const props = defineProps({
    show: {
        type: Boolean,
        default: true,
    },
    data: {
        type: Number,
        default: 0,
    },
})

const formRef = ref<FormInstance>();

const sureFn = () => {
    formRef.value?.validate((valid: boolean) => {
        if (valid) {
            ElMessageBox.confirm("确定要添加该用户吗？", "添加用户", {
                type: "warning",
                confirmButtonText: "确定",
                cancelButtonClass: "取消",
            }).then(() => {
                if (props.data !== 0) {
                    user.updateUserInfoApi(form as IUserModel).then(res => {
                        if (res.code === 200) {
                            ElMessage.success("修改用户成功");
                            searchFormRef.value?.resetFields()
                            emit("hide");
                            emit("refresh")
                        }
                    })
                } else {
                    user.registerUserApi(form).then(res => {
                        if (res.code === 200) {
                            ElMessage.success("添加用户成功");
                            
                            emit("hide");
                            
                            emit("refresh");
                        } else {
                            ElMessage.success(res.message +",请重试")
                        }
                    })
                }
            })
                .catch(() => { })
        } else {
            return false;
        }
    })
}

watch(
    () => props.data,
    () => {
        if (props.data === 0) {
            return;
        }


        user.getUserInfoApi(props.data).then((res) => {
            if (res.code === 200) {

                Object.assign(form, res.data);
            }
        });
    }
);
</script>

<style scoped>

</style>